import { requestSDspotMarket } from "./fetch";
import dayjs from "dayjs";
import { throttle } from 'lodash'
import { saveDataToLocalStorage, getDataFromLocalStorage } from "@src/utils/common";

const appEnv = import.meta.env.VITE_APP_ENV
const messageDistance = 18 // 设置间隔多少分钟内可再次发出告警

/** 根据当前时间和上次发出告警的时间判断是否可发出告警 */
const warnControl = async () => {
 let isSend = true
 const key = 'lastSendWarnTime'

 const dateNow = dayjs().format('YYYY-MM-DD HH:mm:ss')
 const lastSendWarnTime = await getDataFromLocalStorage(key) as string

 if(!lastSendWarnTime) {
  saveDataToLocalStorage(dateNow, key)
  return Promise.resolve(isSend)
 }

 const diffMinute = dayjs(dateNow).diff(lastSendWarnTime, 'minute', true)
 isSend = diffMinute > messageDistance

 if(isSend) saveDataToLocalStorage(dateNow, key)

 return Promise.resolve(isSend)
}

/** 发出告警 */
const warnRobot = async () => {
  const isSend = await warnControl()
  console.log('warnRobot isSend', isSend)
  if(!isSend) return

  const env = appEnv === 'development' ? '测试' : '生产'
  const extraTip = appEnv === 'development' ? '告警测试，请忽略!' : ''

  const robots:Record<string, string> = {
    development: `https://oapi.dingtalk.com/robot/send?access_token=9f0538896a8450c3c26ac264b97e1da7be5ddde0f24df311d347ea5ff3335e5a`,
    production: `https://oapi.dingtalk.com/robot/send?access_token=c2cfc8f4b725401b8b528e1851e7e45c1822330e831310355bcab0322a18088b`
  }
  const message = JSON.stringify({
    "msgtype": "text",
    "text": {
      "content": `${extraTip}【 ${env} 】【 Chrome插件告警 异常 测试平台 】${dayjs().format('YYYY-MM-DD HH:mm:ss')}交易中心，TOKEN已过期。请重新登录！`
    }
  })

  try {
    await requestSDspotMarket(
      robots?.[appEnv] || robots.production,
      message,
      {headers:{'Content-Type':'application/json'}}
    )
  }catch(e) {
    console.error(e)
  }
}

export const warnRobotThrottle = throttle(warnRobot, 5000, {trailing:true, leading: false})